﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JXT.PrimaryKey.Batman.Collections;
using JXT.PrimaryKey.Batman.Domain.Services;
using JXT.PrimaryKey.Batman.Domain.Specifications;
using JXT.PrimaryKey.Batman.Domain.VirtualExchange.Models;
using JXT.PrimaryKey.Batman.Domain.VirtualExchange.Repositories;

namespace JXT.PrimaryKey.Batman.Domain.VirtualExchange.Services.Default
{
    public class UserBindingService : CachedServiceBase<UserBinding>, IUserBindingService
    {
        public void Add(UserBinding entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");
            LoadRepository<IUserBindingRepository>().Add(entity);
        }

        public void Update(UserBinding entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");
            if (entity.Id <= 0)
                throw new ArgumentException("entity has a error id.");
            LoadRepository<IUserBindingRepository>().Update(entity);
        }

        public void Delete(UserBinding entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");
            if (entity.Id <= 0)
                throw new ArgumentException("entity has a error id.");
            LoadRepository<IUserBindingRepository>().Delete(entity.Id);
        }

        public int Count(ISpecification<UserBinding> specification)
        {
            return LoadRepository<IUserBindingRepository>().Count(specification);
        }

        public UserBinding GetSingle(ISpecification<UserBinding> specification)
        {
            var result = LoadRepository<IUserBindingRepository>().GetSingle(specification);
            FillSingle(result);
            return result;
        }

        public UserBinding GetSingleByUserId(int userId)
        {
            var specification = SpecificationFactory.CreateSpecification<UserBinding>();
            specification.And(e => e.UserId == userId);
            var result = LoadRepository<IUserBindingRepository>().GetSingle(specification);
            FillSingle(result);
            return result;
        }

        public IPagedCollection<UserBinding> GetList(IPagedSpecification<UserBinding> specification)
        {
            var list = LoadRepository<IUserBindingRepository>().GetList(specification);
            FillList(list);
            return list;
        }

        protected override void FillSingle(UserBinding entity)
        {
            base.FillSingle(entity);
            if (entity != null)
            {
                entity.Type = LoadService<IBindingTypeService>().GetSingle(entity.TypeId);
            }
        }
    }
}
